package com.wxy.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.wxy.demo.dto.FavoritesTemplateDto;
import com.wxy.demo.dto.UserDto1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2023/3/9 9:58
 */
@RestController
@RequestMapping("/excel")
@Slf4j
public class ExcelController {

    /**
     * 下载
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<UserDto1> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            UserDto1 data = new UserDto1();
            data.setUsername("用户" + i);
            data.setAge(10 + i);
            list.add(data);
        }
        EasyExcel.write(response.getOutputStream(), UserDto1.class)
                .sheet("模板")
                .doWrite(list);
        response.setContentType("application/force-download");//应用程序强制下载
        response.setHeader("Content-Disposition", "attachment;filename=download.xlsx");
    }

    /**
     * 上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), UserDto1.class, new ReadListener<UserDto1>() {
            @Override
            public void invoke(UserDto1 data, AnalysisContext analysisContext) {
                log.info("data = {}", data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.info("所有数据解析完成！");
            }
        }).sheet().doRead();
        return "上传成功：" + file.getOriginalFilename();
    }

    /**
     * 上传对象不能使用 @Accessors(chain = true)
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload1")
    public String upload1(@RequestParam MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), FavoritesTemplateDto.class, new ReadListener<FavoritesTemplateDto>() {
            @Override
            public void invoke(FavoritesTemplateDto data, AnalysisContext analysisContext) {
                log.info("data = {}", data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.info("所有数据解析完成！");
            }
        }).sheet().doRead();
        return "上传成功：" + file.getOriginalFilename();
    }
}
